import axios from 'axios';

export function getAppAccessToken(appId, appSecret) {
    const url = 'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal';
    return axios({
        method: 'POST',
        url: url,
        data: {
            app_id: appId,
            app_secret: appSecret
        }
    }).then(response => {
        // Access token should be in response.data.app_access_token
        return response.data.app_access_token;
    }).catch(error => {
        // Handle errors
        if (error.response) {
            console.error('Error:', error.response.data);
        } else {
            console.error('Error:', error.message);
        }
        // Return null or throw an error, depending on your error-handling strategy
        return null;
    });
}

export function getAccessToken(code, accessToken) {
    const data = JSON.stringify({
        "grant_type": "authorization_code",
        "code": code
    });

    const config = {
        method: 'POST',
        url: 'https://open.feishu.cn/open-apis/authen/v1/oidc/access_token',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${accessToken}`
        },
        data: data
    };

    return axios(config).then(response => {
        console.log(JSON.stringify(response.data));
        return response.data;
    }).catch(error => {
        console.log(error);
        // In this function, the original code throws the error, so let's keep it consistent.
        throw error;
    });
}
 export function buildAuthUrl(appId, redirectUri) {
     const baseUrl = 'https://open.feishu.cn/open-apis/authen/v1/index';
     const queryParams = new URLSearchParams({
         redirect_uri: redirectUri,
         app_id: appId,
     });
     return `${baseUrl}?${queryParams}`;
 }



